package com.bjx.common.captcha.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.bjx.common.captcha.CaptchaContext;
import com.bjx.common.captcha.CaptchaStrategy;
import com.bjx.common.captcha.domain.CaptchaVO;
import com.bjx.common.core.exception.BJXException;
import com.bjx.common.redisson.constant.RedisConstant;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Component
public class CalculateCaptchaStrategy extends CaptchaStrategy {
    @Autowired
    private RedissonClient redissonClient;

    @Override
    public CaptchaVO getCaptcha() {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 40);
        String key = UUID.randomUUID().toString();
        String verCode = lineCaptcha.getCode();
        String imageBase64 = lineCaptcha.getImageBase64Data();
        CaptchaVO captchaVO = new CaptchaVO();
        captchaVO.setCaptchaImage(imageBase64);
        captchaVO.setKey(key);
        RBucket<String> bucket = redissonClient.getBucket(RedisConstant.CAPTCHA + key);
        bucket.set(verCode, CaptchaContext.CAPTCHA_OUT_TIME, TimeUnit.SECONDS);
        return captchaVO;
    }

    @Override
    public Boolean verification(String code, String key) {
        RBucket<String> bucket = redissonClient.getBucket(RedisConstant.CAPTCHA + key);
        if(bucket == null){
            throw new BJXException("验证码已失效");
        }
        String captchaValue = bucket.get();
        return captchaValue.equals(code);
    }
}
